import React, { Component } from 'react'
import { connect } from 'react-redux'
import TextAreaFieldGroup from '../../common/TextAreaFieldGroup';
import { addPost } from '../../actions/postActions'

// 表单
export class PostForm extends Component {
  state = {
    text: '',
    errors: {}
  }
  componentWillReceiveProps (newProps) {
    if (newProps.errors) {
      this.setState({ errors: newProps.errors });
    }
  }
  onChange = (e) => {
    this.setState({ [e.target.name]: e.target.value });
  }
  onSubmit = (e) => {
    e.preventDefault()
    const { user } = this.props.auth;
    const newPost = {
      text: this.state.text,
      name: user.name,
      avatar: user.avatar
    }
    this.props.addPost(newPost);
    this.setState({ text: '' });
  }
  render () {
    const { errors } = this.state;
    return (
      <div className="post-form mb-3">
        <div className="card card-info">
          <div className="card-header bg-info text-white">随便说点啥..</div>
          <div className="card-body">
            <form onSubmit={this.onSubmit}>
              <div className="form-group">
                <TextAreaFieldGroup
                  placeholder="留言说点.."
                  name="text"
                  value={this.state.text}
                  onChange={this.onChange}
                  error={errors.text}
                />
              </div>
              <button type="submit" className="btn btn-dark">
                提交
            </button>
            </form>
          </div>
        </div>
      </div>
    )
  }
}

const mapStateToProps = (state) => ({
  auth: state.auth,
  errors: state.errors
})

const mapDispatchToProps = dispatch => {
  return {
    addPost: (newPost) => {
      dispatch(addPost(newPost))
    }
  }

}

export default connect(mapStateToProps, mapDispatchToProps)(PostForm)
